﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Devonline.Identity;

/// <summary>
/// 用户得到授权后对具体 Action 访问的权限控制过滤器
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizationFilter : Attribute, IAsyncAuthorizationFilter
{
    protected readonly AuthorizationService _authorizationService;
    public AuthorizationFilter(AuthorizationService authorizationService) => _authorizationService = authorizationService;

    /// <summary>
    /// 此处仅针对授权完成后, 判断用户是否有权限访问某个资源
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        if (context.HttpContext.User.Identity.IsAuthenticated && !await _authorizationService.AuthorizeAsync())
        {
            context.Result = new ForbidResult();
        }

        await Task.CompletedTask;
    }
}